<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/1/9 0009
 * Time: 下午 12:17
 */
namespace app\jointly\controller;
use Firebase\JWT\JWT;
use think\Db;
use think\Request;
use think\Response;
header('Content-Type:application/json; charset=utf-8');
header("Access-Control-Allow-Origin: *"); 
class Base extends Push
{
    public $redis;
    public $NoData = '没有更多数据了';
    public $Error = '网络错误';
    public $Key;
    public function __construct()
    {
        parent::__construct();
        $redis = new \Redis();
        $redis->pconnect('127.0.0.1',6379);
        $this->redis = $redis;
        $this->Key   = Request::instance()->action();
    }
    //todo 返回json错误信息
    public function returnError($msg='fail',$code=0){
        return Response::create([
            'code'  =>$code,
            'msg'   =>$msg,
        ],'json');
    }
    //todo 返回json正常格式
    public function returnSuccess($data,$msg='success',$code=1){
        return Response::create([
            'code'  =>$code,
            'msg'   =>$msg,
            'data'  =>$data,
        ],'json');
    }
    //todo 拦截层弹出json
    public function encode($data,$code=-1){
        return json_encode([
            'code'  =>$code,
            'msg'   =>$data,
        ],true);
    }
    //todo 分页
    public function page($data){
        if(empty($data['limit']) || $data['limit'] <10){
            $res['limit'] = 10;
        }else{
            $res['limit'] = $data['limit'];
        }
        if(empty($data['page']) || $data['page'] < 1){
            $res['page'] = 0;
        }else{          
            $res['page'] = ($data['page'] -1)*$res['limit'];
        }
        return $res;
    }
    //todo 循环添加文件到压缩包中
    public function addFileToZip($path,$zip)
    {
        $handler=opendir($path); //打开当前文件夹由$path指定。
        while(($filename=readdir($handler))!==false)
        {
            if($filename != "." && $filename != "..")
            {
                //文件夹文件名字为'.'和‘..’，不要对他们进行操作
                if(is_dir($path."/".$filename))
                {
                    // 如果读取的某个对象是文件夹，则递归
                    $this->addFileToZip($path."/".$filename, $zip);
                }else{
                    //将文件加入zip对象
                    $zip->addFile($path."/".$filename);
                }
            }
        }
        @closedir($path);
    }
    //todo 上传文件
    public function putFile($data){
        //todo 限制文件上传类型
        $type = [
            'image/jpeg',
            'image/png',
        ];
        //todo 设置文件上传大小
        $size =  4204800;
        //todo 设置图片存储路径
        $path ='./img/';
        //todo 设置图片地址
        if(empty($data))                   return $this->returnError('请上传文件');
        if(!in_array($data['type'],$type)) return $this->returnError('文件格式错误');
        if($data['size'] >= $size)         return $this->returnError('文件过大');
        if(!file_exists($path)){
            $mkdir = mkdir($path,0777,true);
            if(!$mkdir)return $this->returnError('文件创建失败');
        }
        $name = time().rand(1000,9999);
        $Suffix = explode('/',$data['type'])[1];
        $filename =$path.$name.'.'.$Suffix;
        if(file_exists($filename))         return $this->returnError('文件已存在');
        $save = move_uploaded_file($data['tmp_name'],$filename);
        if($save) {
            return $this->returnSuccess('http://47.52.188.179/public/'.$filename);
        }else{
            return $this->returnError('图片上传失败');
        }
    }
    //todo 获取随机字符串
    public function GetRandomStr($len, $special=false){
        $chars = array(
            "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
            "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
            "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
            "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
            "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
            "3", "4", "5", "6", "7", "8", "9"
        );
        if($special){
            $chars = array_merge($chars, array(
                    "!", "@", "#", "$", "?", "|", "{",
                    "/", ":", ";", "%", "^", "&", "*",
                    "(", ")", "-", "_", "[", "]", "}",
                    "<", ">", "~", "+", "=", ","
                )
            );
        }
        $charsLen = count($chars) - 1;
        shuffle($chars);                                //打乱数组顺序
        $str = '';
        for($i=0; $i<$len; $i++){
            $str .= $chars[mt_rand(0, $charsLen)];            //随机取出一位
        }
        return $str;
    }
    //todo JWT加密
    public function JWT_encryption($key,$data){
        return JWT::encode($data,$key);
    }
    //todo JWT解密
    public function JWT_decrypt ($key,$data){
        return JWT::decode($data,$key,['HS256']);
    }
    //todo 发送网络请求
    public function cUrl($url,$data = null){
        $UserAgent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36';
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_USERAGENT, $UserAgent);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);// 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);// 从证书中检查SSL加密算法是否存在
        if (!empty($data)){//post方式
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, ($data));// Post提交的数据包x
        }
        //获取采集结果
        $output = curl_exec($curl);
        //关闭cURL链接
        curl_close($curl);
        return $output;
    }
    //todo 获取验证码
    public function GetYzm($phone,$type){
        $typeKey = $phone.$type;
        $same_key = $phone.'_same_'.$type;
        if($this->redis->get($same_key))return $this->returnError('60秒内请不要重复发送验证码');
        $res = '';
        for ($i=0;$i<=3;$i++){
            $res .= rand(0,9);
        }
        $ress = Sms::Send($phone,$res);      	
        if($ress != 'OK')return $this->returnError($ress);
        $this->redis->set($same_key,'1',60);
        $this->redis->set($typeKey,$res,600);
        return $this->returnSuccess(null,'发送成功');
    }
    //todo 星期转换
    public function weekChange($week){
        return str_replace([1,2,3,4,5,6,0],['one','two','three','four','five','six','seven'],date('w',$week));
    }

    /* todo 积分日志
     * uid 用户id
     * desc 描述
     * type 1收入 2支出
     * integral 积分数
     */
    public function IntegralLog($uid,$desc,$type,$integral){
        $set = [
            'uid'   =>$uid,
            'desc'  =>$desc,
            'type'  =>$type,
            'integral'=>$integral,
            'create_time'  =>time(),
        ];

        Db::name('integral_log')->insert($set);
        return true;
    }

    //todo 转化为CNY
    public function ChangeCNY($price){
        $ref = Db::name('common')->where(['type'=>99])->value('content');
        $Cny = round($price*$ref,2);
        return $Cny;
    }

    //todo 发送消息
    public function SendMsg($message,$user,$model){
      	//var_dump($user,$message);die;
      	$type = isset($message['type']) ? $message['type'] :1;
      	if($type != '0')$type = 1;
        $msgset = [
            'title'=>$message['title'],
            'content'=>$message['content'],
            'time'=>time(),
            'type'  =>$type,
            'model' =>$model,
        ];
      //	var_dump($msgset);die;
        Db::startTrans();
        try{
            $me_id = Db::name('message')->insertGetId($msgset);
            $set = [];
            for ($i=0;$i<count($user);$i++){
                $set[] = ['uid'=>$user[$i],'me_id'=>$me_id];
            }
            Db::name('message_user')->insertAll($set);
            Db::commit();
            return 1;
        }catch (\Exception $e){
            Db::rollback();
            return $e->getMessage();
        }
    }

    public function GetPushReg($uid){
        $time = date('Hi',time());
        $map = [
            'a.uid'=>['in',$uid],
            'a.stime'=>['<',$time],
            'a.etime'=>['>',$time],
            'a.msg'  =>1,
            'b.reg_id'=>['not in',null],
        ];
        $reg_id = Db::name('user_msg')
            ->alias('a')
            ->join('user b','a.uid=b.uid')
            ->where($map)
            ->column('b.reg_id');
        if($reg_id)return $reg_id;
        return false;
    }
  
  	public function ChangePrice($price){
    	if($price > 10){
        	$price = round($price,2);
        }elseif($price >0.1){
        	$price = round($price,3);
        }elseif($price < 0.1){
        	$price = substr($price,0,6);
        }
      	return $price;
    }
}